//
//  AppDelegate.m
//  cyydt
//
//  Created by chu on 2019/1/14.
//  Copyright © 2019 chu. All rights reserved.
//

#import "AppDelegate.h"
#import "CYStateOneViewController.h"
#import "LCNewFeatureVC.h"
#import "JLAuthorizationManager.h"
@interface AppDelegate ()<TencentSessionDelegate, WXApiDelegate, LCNewFeatureVCDelegate>

@end

@implementation AppDelegate


+ (instancetype)sharedAppDelegate
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [ChangeLanguage initUserLanguage];//初始化应用语言
    [self initThirdParty];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self initYinDaoYe];
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)initYinDaoYe{
#pragma mark 1. 是否应该显示新特性界面
    
    BOOL showNewFeature = [LCNewFeatureVC shouldShowNewFeature];
    
//    // 演示--每次都进入新特性界面, 实际项目不需要此句代码
//    showNewFeature = YES;
    
    if (showNewFeature) {   // 如果需要显示新特性界面
        __weak typeof(self) weakSelf = self;
        
#pragma mark 2.1. 方式一: 点击添加的按钮进入主界面
        
        // 进入主界面按钮
        UIButton *enterBtn = [[UIButton alloc] init];
        [enterBtn setBackgroundColor:[UIColor clearColor]];
        [enterBtn setTitle:@"" forState:UIControlStateNormal];
        [enterBtn setFrame:CGRectMake(0, 0, 220, 50)];
        enterBtn.layer.cornerRadius = 25;
        enterBtn.layer.masksToBounds = YES;
        enterBtn.center = CGPointMake(kWindowW / 2, kWindowH - 75);
        [enterBtn addTarget:self action:@selector(didClickedBtn) forControlEvents:UIControlEventTouchUpInside];
        
        LCNewFeatureVC *newFeatureVC = [LCNewFeatureVC newFeatureWithImageName:@"yindaoye"
                                                                    imageCount:4
                                                               showPageControl:NO
                                                                   enterButton:enterBtn];
        newFeatureVC.showSkip = YES;
        newFeatureVC.skipBlock = ^(void) {
            if (![[NSUserDefaults standardUserDefaults] objectForKey:@"showYinDao"]) {
                [weakSelf enterMainVC];
            }else{
                [weakSelf enterRootVc];
            }
        };
        
#pragma mark 4. 设置新特性界面为当前窗口的根视图控制器
        
        self.window.rootViewController = newFeatureVC;
        
    } else {    // 如果不需要显示新特性界面
        
        [self enterRootVc];
    }
}
#pragma mark - 点击了进入主界面的按钮

- (void)didClickedBtn {
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"showYinDao"]) {
        [self enterMainVC];
    }else{
        [self enterRootVc];
    }
}
- (void)enterRootVc{
    ZTTabBarController *tab = [[ZTTabBarController alloc] init];
    [self restoreRootViewController:tab];

//    self.window.rootViewController = tab;
}

#pragma mark - 进入主界面

- (void)enterMainVC {
    CYStateOneViewController *two = [[CYStateOneViewController alloc] init];
    ZTNavigationController *nav = [[ZTNavigationController alloc] initWithRootViewController:two];
    [self restoreRootViewController:nav];
}
- (void)restoreRootViewController:(UIViewController *)rootViewController {
    
    [UIView transitionWithView:self.window duration:0.7f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        self.window.rootViewController = rootViewController;
        [UIView setAnimationsEnabled:oldState];
        
    } completion:nil];
}
/**
 *  代理方法，回调当前页码
 *
 *  @param newFeatureVC 控制器
 *  @param page         当前页码
 */
- (void)newFeatureVC:(LCNewFeatureVC *)newFeatureVC page:(NSInteger)page {
    NSLog(@"%@ -> Page: %d", newFeatureVC, (int)page);
}

- (void)initThirdParty{
    //获取网络权限
    [[JLAuthorizationManager defaultManager] JL_requestAuthorizationWithAuthorizationType:JLAuthorizationTypeCellularNetWork authorizedHandler:^{
        
    } unAuthorizedHandler:^{
        
    }];
    //获取相册权限
    [[JLAuthorizationManager defaultManager] JL_requestAuthorizationWithAuthorizationType:JLAuthorizationTypePhotoLibrary authorizedHandler:^{
        
    } unAuthorizedHandler:^{
        
    }];
    //获取相机权限
    [[JLAuthorizationManager defaultManager] JL_requestAuthorizationWithAuthorizationType:JLAuthorizationTypeCamera authorizedHandler:^{
        
    } unAuthorizedHandler:^{
        
    }];
    // Override point for customization after application launch.
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.enableAutoToolbar = NO;
    manager.shouldShowToolbarPlaceholder = NO;
    
    BOOL qqSucess = [[TencentOAuth alloc] initWithAppId:@"101498694" andDelegate:self];
    if (qqSucess) {
        NSLog(@"qq注册成功");
    }else{
        NSLog(@"qq注册失败");
    }
    BOOL wxSucess = [WXApi registerApp:@"wx51d9825eb2ff1100"];
    if (wxSucess) {
        NSLog(@"微信注册成功");
    }else{
        NSLog(@"微信注册失败");
    }
    
}

//iOS9.0以前使用
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSLog(@"url.host -- %@",url.host);
    if ([url.host isEqualToString:@"qzapp"]) {
        return  [TencentOAuth HandleOpenURL:url];
    }
    if ([url.host isEqualToString:@"oauth"]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
    
}

// 9.0以后使用新API接口
- (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary *)options{
    NSLog(@"url.host -- %@",url.host);
    if ([url.host isEqualToString:@"qzapp"]) {
        return  [TencentOAuth HandleOpenURL:url];
    }
    if ([url.host isEqualToString:@"oauth"]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

-(void) onResp:(BaseResp*)resp{
    /*
     enum  WXErrCode {
     WXSuccess           = 0,    成功
     WXErrCodeCommon     = -1,  普通错误类型
     WXErrCodeUserCancel = -2,    用户点击取消并返回
     WXErrCodeSentFail   = -3,   发送失败
     WXErrCodeAuthDeny   = -4,    授权失败
     WXErrCodeUnsupport  = -5,   微信不支持
     };
     */
    if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。
        if (resp.errCode == 0) {  //成功。
            SendAuthResp *resp2 = (SendAuthResp *)resp;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"wxLogin" object:resp2.code];
        }else{ //失败
            [[UIApplication sharedApplication].keyWindow makeToast:@"授权失败" duration:1.5 position:CSToastPositionCenter];
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    if ([YLUserInfo isLogIn]) {
        [self getUserInfosWithComplecation:nil];
    }
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#pragma mark - 获取用户信息
- (void)getUserInfosWithComplecation:(ComplecationVoidBlock)block{
    if (![YLUserInfo isLogIn]) {
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"userInfo"];
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:nil ResponseObject:^(NSDictionary *responseResult) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"获取用户信息 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSString *token = [YLUserInfo shareUserInfo].token;
                if (responseResult[@"data"]) {
                    NSDictionary *object = responseResult[@"data"];
                    NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:object];
                    [muDic setObject:token forKey:@"token"];
                    [YLUserInfo getuserInfoWithDic:muDic];
                    if (block) {
                        block();
                    }
                }
                
            }else{
                
            }
        }
    }];
}
#pragma mark - 代码中用以下方法push，pop，present
// 获取当前活动的navigationcontroller
- (UINavigationController *)navigationViewController
{
    if ([self.window.rootViewController isKindOfClass:[UINavigationController class]])
    {
        return (UINavigationController *)self.window.rootViewController;
    }
    else if ([self.window.rootViewController isKindOfClass:[UITabBarController class]])
    {
        UIViewController *selectVc = [((UITabBarController *)self.window.rootViewController) selectedViewController];
        if ([selectVc isKindOfClass:[UINavigationController class]])
        {
            return (UINavigationController *)selectVc;
        }
    }
    return nil;
}

- (UIViewController *)topViewController
{
    UINavigationController *nav = [self navigationViewController];
    return nav.topViewController;
}

- (void)pushViewController:(UIViewController *)viewController
{
    @autoreleasepool
    {
        viewController.hidesBottomBarWhenPushed = YES;
        [[self navigationViewController] pushViewController:viewController animated:YES];
    }
}

- (void)pushViewController:(UIViewController *)viewController withBackTitle:(NSString *)title
{
    @autoreleasepool
    {
        viewController.hidesBottomBarWhenPushed = YES;
        [[self navigationViewController] pushViewController:viewController withBackTitle:title animated:YES];
    }
}

- (void)pushViewController:(UIViewController *)viewController withBackTitle:(NSString *)title backAction:(CommonVoidBlock)action
{
    @autoreleasepool
    {
        viewController.hidesBottomBarWhenPushed = YES;
        [[self navigationViewController] pushViewController:viewController withBackTitle:title action:action animated:NO];
    }
}

- (UIViewController *)popViewController
{
    return [[self navigationViewController] popViewControllerAnimated:YES];
}
- (NSArray *)popToRootViewController
{
    return [[self navigationViewController] popToRootViewControllerAnimated:YES];
}

- (NSArray *)popToViewController:(UIViewController *)viewController
{
    return [[self navigationViewController] popToViewController:viewController animated:YES];
}

- (void)presentViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))completion
{
    UIViewController *top = [self topViewController];
    
    if (vc.navigationController == nil)
    {
        if ([vc isKindOfClass:NSClassFromString(@"PGDatePickManager")] || [vc isKindOfClass:NSClassFromString(@"ZLGestureLockViewController")]) {
            [top presentViewController:vc animated:animated completion:completion];
        }else{
            ZTNavigationController *nav = [[ZTNavigationController alloc] initWithRootViewController:vc];
            [top presentViewController:nav animated:animated completion:completion];
        }
    }
    else
    {
        [top presentViewController:vc animated:animated completion:completion];
    }
}

- (void)dismissViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))completion
{
    if (vc.navigationController != [AppDelegate sharedAppDelegate].navigationViewController)
    {
        [vc dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        [vc.navigationController popViewControllerAnimated:YES];
    }
}


- (void)tencentDidLogin {
    
}

- (void)tencentDidNotLogin:(BOOL)cancelled {
    
}

- (void)tencentDidNotNetWork {
    
}

@end
